// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package src.client;

import src.ocsf.client.*;
import src.common.*;
import java.io.*;

/**
 * This class overrides some of the methods defined in the abstract
 * superclass in order to give more functionality to the client.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;
 * @author Fran&ccedil;ois B&eacute;langer
 * @version July 2000
 */
public class ChatClient extends AbstractClient
{
  //Instance variables **********************************************
  
  /**
   * The interface type variable.  It allows the implementation of 
   * the display method in the client.
   */
  ChatIF clientUI; 

  /**
   * File to send to the server
   */
  private File fileToSend;
  private FileInputStream fis = null;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the chat client.
   *
   * @param host The server to connect to.
   * @param port The port number to connect on.
   * @param clientUI The interface type variable.
   */
  
  public ChatClient(String host, int port, ChatIF clientUI) 
    throws IOException 
  {
    super(host, port); //Call the superclass constructor
    this.clientUI = clientUI;
    openConnection();
  }

  //Accessing Methodes ++++++++++++++++++++++++++++++++++++++++++++++
  /**
   * This method send a file to the server
   * @param file The file send to the server.
   */
  private void sendFile(String key,String message) throws IOException
  {
	  //sendToServer((Object)fileToSend);
	  //clientUI.display("Can't send file : " + message + "\n" + e.getMessage());
	  
	  byte[] buffer= new byte[4096];
      int bytes = 0;
      try
      {
    	  //Début de transfrt du fichier
    	  //sendToServer("/TakeF%" + fileToSend.getName());
    	  clientUI.display("Sending : " + fileToSend.getName() + " ...");
    	  //Copie du fichier dans le flux de sortie   
          while((bytes = fis.read(buffer)) != -1)
              sendToServer("/TakeF%" + new String(buffer));
          fis.close();
      }
      catch(IOException ioe)
      {
          System.out.println("Erreur d'IO : "+ioe);
      }
  }
  
  //Instance methods ************************************************
    
  /**
   * This method handles all data that comes in from the server.
   *
   * @param msg The message from the server.
   */
  public void handleMessageFromServer(Object msg) 
  {
	  //clientUI.display(msg.toString());
		  String[] message = msg.toString().split("%");
		  if (message[0].equals("/OKSendF"))
		  {
			  clientUI.display(message[0]);
			  try {
				  sendFile(message[0],message[1]);
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
  }

  /**
   * This method handles all data coming from the UI            
   *
   * @param message The message from the UI.    
   */
  public void handleMessageFromClientUI(String message)
  {
	String[] msg = message.toString().split("%");
    try
    {
  	  	///SendF%C:\Users\Adam\Desktop\test.txt
  	  	if (msg[0].equals("/SendF"))
  	  	{
  	    	fileToSend = new File(msg[1]);
  	  	  	fis = new FileInputStream(fileToSend);
  	  	  	sendToServer(msg[0] + "%" + fileToSend.getName() + "%" + (fileToSend.length()/4096 + 1));  	  		
  	  	}
        if (msg[0].equals("/OKSendF"))
        	sendFile(msg[0],msg[1]);
    }
    catch(IOException e)
    {
      clientUI.display
        ("Could not send message to server.  Terminating client.");
      quit();
    }
  }
  
  /**
   * This method terminates the client.
   */
  public void quit()
  {
    try
    {
      closeConnection();
    }
    catch(IOException e) {}
    System.exit(0);
  }

@Override
protected void connectionException(Exception exception) {
	// TODO Auto-generated method stub
	super.connectionException(exception);
	clientUI.display
    ("Server not responding.");
	this.quit();
}

@Override
protected void connectionClosed() {
	// TODO Auto-generated method stub
	super.connectionClosed();
	clientUI.display
    ("Connection closed.  Terminating clients.");
}
  
}
//End of ChatClient class